<template>
  <el-dialog v-if="load" :close-on-click-modal="false" title="邮箱模板设置" v-model="visible" align-center width="500px" @close="handleClose">
    <el-form label-position="top">
      <el-form-item label="邮件发送模板">
        <div class="flex items-center w-full">
          <VSelect v-model="form.et_id" type="email" class="flex-1" filterable clearable @change="templateChange" />
          <el-popover placement="bottom" :width="400" trigger="click">
            <template #reference>
              <el-button :disabled="!templateValue" class="m-2" link type="primary">预览</el-button>
            </template>
            <pre class="whitespace-pre-wrap">{{ templateValue }}</pre>
          </el-popover>
        </div>
      </el-form-item>
      <el-form-item label="抄送人配置">
        <VCascader v-if="visible" v-model="form.copy_user_ids" placeholder="采购人员" multiple :collapse-tags="false"
          :max-collapse-tags="2" filterable clearable class="w-full" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const form = ref({})

const emit = defineEmits(['close', 'success'])

const templateValue = ref('')
const templateChange = ({ value }) => {
  api.preview({et_id: value}).then(res => {
    templateValue.value = res.data
  })
}

// 打开弹窗
const open = async (e_ids) => {
  if (e_ids && !e_ids.length) {
    ElMessage.warning('请先选择行!')
    return
  }
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  templateValue.value = ''
  form.value = { e_ids }
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const submit = () => {
  loadings.submit = true
  api.updateUser(form.value).then(res => {
    ElMessage.success('操作成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.submit = false
  })
}

defineExpose({ open })
</script>